<template>
  <div class="dispatch-rule">
    <h1>派单规则管理</h1>
    <div class="table-container">
      <!-- 添加刷新和添加按钮 -->
      <div style="margin-bottom: 15px;">
        <el-button type="primary" @click="fetchDispatchRules" :loading="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </el-button>
        <el-button type="primary" @click="showAddForm">添加规则</el-button>
      </div>
      
      <!-- 派单规则表格 -->
      <el-table :data="dispatchRules" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="规则ID" width="100" />
        <el-table-column prop="ruleName" label="规则名称" width="150" />
        <el-table-column prop="type" label="规则类型" width="100">
          <template #default="scope">
            {{ getRuleTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="ruleDesc" label="规则描述" width="200" />
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column prop="matchMode" label="匹配模式" width="120">
          <template #default="scope">
            {{ getMatchModeText(scope.row.matchMode) }}
          </template>
        </el-table-column>
        <el-table-column label="过滤条件" width="300">
          <template #default="scope">
            <div v-for="(filter, index) in scope.row.filters" :key="index" class="filter-item-mini">
              <el-tag type="info" size="small">{{ getFilterTypeName(filter.filterType) }}</el-tag>
              <span style="margin: 0 5px;">{{ filter.operator }}</span>
              <span>{{ filter.filterVal }} {{ filter.unit }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="是否启用" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" @click="showDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="showEditForm(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleRuleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 添加/编辑派单规则对话框 -->
    <el-dialog 
      :title="isEdit ? '编辑派单规则' : '添加派单规则'" 
      v-model="dialogFormVisible" 
      width="700px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="ruleForm" 
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择规则类型">
            <el-option label="普通" :value="0"></el-option>
            <el-option label="紧急" :value="1"></el-option>
            <el-option label="VIP" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则描述" prop="ruleDesc">
          <el-input v-model="form.ruleDesc" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number 
            v-model="form.priority" 
            :min="1" 
            :max="100" 
            controls-position="right"
          ></el-input-number>
          <div class="priority-tip">数值越小优先级越高</div>
        </el-form-item>
        <el-form-item label="匹配模式" prop="matchMode">
          <el-select v-model="form.matchMode" placeholder="请选择匹配模式">
            <el-option label="距离优先" :value="0"></el-option>
            <el-option label="星级优先" :value="1"></el-option>
            <el-option label="单量优先" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        
        <!-- 过滤条件 -->
        <el-divider>过滤条件</el-divider>
        <div v-for="(filter, index) in form.filters" :key="filter.filterType" class="filter-item">
          <el-form-item 
            :label="getFilterTypeName(filter.filterType)" 
            :prop="'filters.' + index + '.filterVal'"
            :rules="{ required: true, message: '请输入条件值', trigger: 'blur' }"
          >
            <div style="display: flex; align-items: center;">
              <el-input-number 
                v-model="filter.sort" 
                :min="1" 
                :max="3" 
                controls-position="right" 
                style="width: 80px; margin-right: 10px;"
                size="small"
              ></el-input-number>
              <el-tooltip content="执行顺序，数字越小优先级越高" placement="top">
                <i class="el-icon-info" style="margin-right: 10px; color: #409eff; cursor: help;"></i>
              </el-tooltip>
              <el-select v-model="filter.operator" placeholder="运算符" style="width: 100px;">
                <el-option label="大于" value=">"></el-option>
                <el-option label="小于" value="<"></el-option>
                <el-option label="等于" value="="></el-option>
                <el-option label="大于等于" value=">="></el-option>
                <el-option label="小于等于" value="<="></el-option>
              </el-select>
              <el-input v-model="filter.filterVal" placeholder="值" style="width: 150px; margin: 0 10px;"></el-input>
              <span>{{ filter.unit }}</span>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 规则详情对话框 -->
    <el-dialog 
      title="派单规则详情" 
      v-model="detailDialogVisible" 
      width="700px"
    >
      <el-form label-width="100px">
        <el-form-item label="规则ID">
          <span>{{ currentRule.id }}</span>
        </el-form-item>
        <el-form-item label="规则名称">
          <span>{{ currentRule.ruleName }}</span>
        </el-form-item>
        <el-form-item label="规则类型">
          <span>{{ getRuleTypeText(currentRule.type) }}</span>
        </el-form-item>
        <el-form-item label="规则描述">
          <span>{{ currentRule.ruleDesc }}</span>
        </el-form-item>
        <el-form-item label="优先级">
          <span>{{ currentRule.priority }}</span>
        </el-form-item>
        <el-form-item label="匹配模式">
          <span>{{ getMatchModeText(currentRule.matchMode) }}</span>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-tag :type="currentRule.status === 1 ? 'success' : 'danger'">
            {{ currentRule.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ currentRule.createTime }}</span>
        </el-form-item>
        <el-form-item label="更新时间">
          <span>{{ currentRule.updateTime }}</span>
        </el-form-item>
        
        <!-- 过滤条件详情 -->
        <el-divider>过滤条件</el-divider>
        <div v-for="(filter, index) in currentRule.filters" :key="index" class="filter-item">
          <el-form-item :label="getFilterTypeName(filter.filterType)">
            <span>{{ filter.operator }} {{ filter.filterVal }} {{ filter.unit }}</span>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getDispatchRuleListAPI, 
  createDispatchRuleAPI, 
  updateDispatchRuleAPI, 
  deleteDispatchRuleAPI,
  updateDispatchStatusAPI
} from '@/apis/order.js'

export default {
  name: 'DispatchRule',
  data() {
    const filters = [
      { 
        filterType: 0,  // 星级
        operator: '>=', 
        filterVal: '', 
        unit: '星',
        sort: 1
      },
      { 
        filterType: 1,  // 单量
        operator: '>=', 
        filterVal: '', 
        unit: '个',
        sort: 2
      },
      { 
        filterType: 2,  // 地理位置/距离
        operator: '>=', 
        filterVal: '', 
        unit: '公里',
        sort: 3
      }
    ].sort((a, b) => a.sort - b.sort);
    
    return {
      dispatchRules: [],
      loading: false,
      dialogFormVisible: false,
      detailDialogVisible: false,
      isEdit: false,
      form: {
        id: undefined,
        ruleName: '',
        type: 0,
        ruleDesc: '',
        priority: 1,
        matchMode: 0,
        status: 1,
        filters: filters
      },
      currentRule: {
        id: undefined,
        ruleName: '',
        type: 0,
        ruleDesc: '',
        priority: 1,
        matchMode: 0,
        status: 1,
        filters: filters,
        createTime: '',
        updateTime: ''
      },
      rules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择规则类型', trigger: 'change' }
        ],
        ruleDesc: [
          { required: true, message: '请输入规则描述', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' }
        ],
        matchMode: [
          { required: true, message: '请选择匹配模式', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.fetchDispatchRules()
  },
  methods: {
    // 获取规则类型文本
    getRuleTypeText(type) {
      switch(type) {
        case 0: return '普通';
        case 1: return '紧急';
        case 2: return 'VIP';
        default: return '未知';
      }
    },
    
    // 获取过滤条件类型名称
    getFilterTypeName(type) {
      switch(type) {
        case 0: return '星级';
        case 1: return '单量';
        case 2: return '距离';
        default: return '未知';
      }
    },
      
    // 获取匹配模式文本
    getMatchModeText(mode) {
      switch(mode) {
        case 0: return '距离优先';
        case 1: return '星级优先';
        case 2: return '单量优先';
        default: return '未知';
      }
    },
    
    // 显示详情
    showDetail(row) {
      // 深拷贝数据，避免影响原数据
      const detailData = JSON.parse(JSON.stringify(row));
      
      // 确保filters是数组
      if (!Array.isArray(detailData.filters)) {
        if (typeof detailData.filters === 'string') {
          try {
            detailData.filters = JSON.parse(detailData.filters);
          } catch (e) {
            console.error('解析过滤条件失败:', e);
            detailData.filters = [];
          }
        } else {
          detailData.filters = [];
        }
      }
      
      // 按sort字段排序
      detailData.filters.sort((a, b) => a.sort - b.sort);
      
      // 设置默认匹配模式
      if (detailData.matchMode === undefined) {
        detailData.matchMode = 0;
      }
      
      this.currentRule = detailData;
      this.detailDialogVisible = true;
    },
    
    // 获取派单规则列表
    async fetchDispatchRules() {
      this.loading = true;
      try {
        const res = await getDispatchRuleListAPI();
        if (res.code === 0) {
          // 处理数据，确保filters是数组
          const rules = res.data.map(rule => {
            if (typeof rule.filters === 'string') {
              try {
                rule.filters = JSON.parse(rule.filters);
              } catch (e) {
                console.error('解析过滤条件失败:', e);
                rule.filters = [];
              }
            }
            return rule;
          });
          this.dispatchRules = rules;
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取派单规则列表失败'
          });
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取派单规则列表失败: ' + (error.msg || error.message || '未知错误')
        });
        console.error('获取派单规则列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    // 显示添加表单
    showAddForm() {
      // 重置表单
      this.form = {
        id: undefined,
        ruleName: '',
        type: 0,
        ruleDesc: '',
        priority: 1,
        matchMode: 0,
        status: 1,
        filters: [
          { 
            filterType: 0,  // 星级
            operator: '>=', 
            filterVal: '', 
            unit: '星',
            sort: 1
          },
          { 
            filterType: 1,  // 单量
            operator: '>=', 
            filterVal: '', 
            unit: '个',
            sort: 2
          },
          { 
            filterType: 2,  // 地理位置/距离
            operator: '>=', 
            filterVal: '', 
            unit: '公里',
            sort: 3
          }
        ].sort((a, b) => a.sort - b.sort)
      };
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    
    // 显示编辑表单
    showEditForm(row) {
      // 深拷贝数据，避免影响原数据
      const editData = JSON.parse(JSON.stringify(row));
      
      // 确保filters是数组
      if (!Array.isArray(editData.filters)) {
        if (typeof editData.filters === 'string') {
          try {
            editData.filters = JSON.parse(editData.filters);
          } catch (e) {
            console.error('解析过滤条件失败:', e);
            editData.filters = [];
          }
        } else {
          editData.filters = [];
        }
      }
      
      // 确保每个filter都有默认值
      const defaultFilters = [
        { 
          filterType: 0,  // 星级
          operator: '>=', 
          filterVal: '', 
          unit: '星',
          sort: 1
        },
        { 
          filterType: 1,  // 单量
          operator: '>=', 
          filterVal: '', 
          unit: '个',
          sort: 2
        },
        { 
          filterType: 2,  // 地理位置/距离
          operator: '>=', 
          filterVal: '', 
          unit: '公里',
          sort: 3
        }
      ];
      
      // 合并现有数据和默认数据
      defaultFilters.forEach(defaultFilter => {
        const existingFilter = editData.filters.find(f => f.filterType === defaultFilter.filterType);
        if (existingFilter) {
          defaultFilter.operator = existingFilter.operator;
          defaultFilter.filterVal = existingFilter.filterVal;
          defaultFilter.sort = existingFilter.sort || defaultFilter.sort;
        }
      });
      
      editData.filters = defaultFilters.sort((a, b) => a.sort - b.sort);
      
      this.form = editData;
      this.isEdit = true;
      this.dialogFormVisible = true;
    },
    
    // 提交表单
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          try {
            // 准备提交数据
            const submitData = {
              ...this.form
            };
            
            let res;
            if (this.isEdit) {
              // 编辑
              res = await updateDispatchRuleAPI(submitData);
            } else {
              // 添加
              res = await createDispatchRuleAPI(submitData);
            }
            
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: this.isEdit ? '编辑成功' : '添加成功'
              });
              this.dialogFormVisible = false;
              this.fetchDispatchRules(); // 刷新列表
            } else {
              this.$message({
                type: 'error',
                message: res.msg || (this.isEdit ? '编辑失败' : '添加失败')
              });
            }
          } catch (error) {
            this.$message({
              type: 'error',
              message: (error.msg || error.message || '未知错误') + (this.isEdit ? '编辑失败' : '添加失败')
            });
            console.error(this.isEdit ? '编辑失败:' : '添加失败:', error);
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    
    // 切换规则状态
    async toggleRuleStatus(row) {
      this.$confirm(
        `确定要${row.status === 1 ? '禁用' : '启用'}派单规则"${row.ruleName}"吗？`, 
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const updatedRule = {
            id: row.id,
            status: row.status === 1 ? 0 : 1
          }
          
          await updateDispatchStatusAPI(updatedRule)
          
          row.status = updatedRule.status
          row.updateTime = new Date().toLocaleString()
          
          this.$message({
            type: 'success',
            message: `${row.status === 1 ? '启用' : '禁用'}派单规则成功!`
          })
        } catch (error) {
          // 处理业务异常
          const errorMsg = error.msg || error.message || '未知错误'
          this.$message({
            type: 'error',
            message: (row.status === 1 ? '禁用' : '启用') + '派单规则失败: ' + errorMsg
          })
          console.error((row.status === 1 ? '禁用' : '启用') + '派单规则失败:', error)
        }
      }).catch(() => {
        // 用户取消操作
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    
    // 删除派单规则
    handleDelete(row) {
      this.$confirm(`确定要删除派单规则"${row.ruleName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteDispatchRuleAPI(row.id)
          
          this.$message({
            type: 'success',
            message: '删除派单规则成功!'
          })
          
          // 刷新列表
          await this.fetchDispatchRules()
        } catch (error) {
          const errorMsg = error.msg || error.message || '未知错误'
          this.$message({
            type: 'error',
            message: '删除派单规则失败: ' + errorMsg
          })
          console.error('删除派单规则失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.dispatch-rule {
  padding: 20px;
  background-color: #f5f5f5;
}

.dispatch-rule h1 {
  margin-top: 0;
  color: #2c3e50;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

.priority-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
}

.filter-item {
  margin-bottom: 15px;
}

.filter-item-mini {
  margin-bottom: 5px;
}

.filter-item-mini:last-child {
  margin-bottom: 0;
}

/* 拖拽手柄样式 */
.drag-handle {
  cursor: grab;
  padding: 2px 6px;
  margin-right: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  color: #666;
  font-size: 12px;
  user-select: none;
  transition: all 0.2s ease;
}

.drag-handle:hover {
  background-color: #e0e0e0;
  color: #333;
}
</style>